package com.three.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.three.entity.User;
import com.three.service.UserService;

@Controller
@RequestMapping("/users")
public class UserController {

	@Autowired
	UserService userService;
	private static Logger logger = Logger.getLogger(UserController.class); 
	
	@RequestMapping("/login")
	public void login(@RequestBody User user,
			HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		JSONObject obj = userService.login(user);
		System.out.println(obj.toString());
		out.write(obj.toString());
	}
	
	@RequestMapping("/findClassmates")
	@ResponseBody
	public User findClassmates(String phone){
		User user = new User();
		user = userService.findUserWithClassmates(phone);
		return user;
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping(value="/uploadIcon",produces="application/json;charset=utf-8")
	@ResponseBody
	public void uploadIcon(HttpServletRequest request,
			MultipartFile file,
			Integer uid,
			PrintWriter out){
		String result = userService.uploadIcon(request,file,uid);
		out.write(result);
		out.close();
	}
	
	@RequestMapping("/register")
	@ResponseBody
	public void register(@RequestBody User user,PrintWriter out){
		String result =userService.register(user);
		out.write(result);
		out.close();
	}
	
	@RequestMapping("/checkPhone")
	@ResponseBody
	public int checkPhone(String phone){
		return userService.checkPhone(phone);
	}
	
	@RequestMapping("/changeName")
	@ResponseBody
	public int  changeName(String userName,String uid){
		int code=userService.changeUserName(userName, uid);
		return code;
	}
	
	@RequestMapping("/changeCampus")
	@ResponseBody
	public int  changeCampus(String campus,String uid){
		int code=userService.changeCampus(campus, uid);
		return code;
	}
	
	@RequestMapping("/changeSno")
	@ResponseBody
	public int  changeSno(String sno,String uid){
		int code=userService.changeSno(sno, uid);
		return code;
	}
	
	@RequestMapping("/changePwd")
	@ResponseBody
	public void  changePwd(String oPwd,
			String uPwd,
			Integer uid,
			PrintWriter out){
		String result =  userService.changePwd(oPwd, uPwd, uid);
		out.write(result);
		out.close();
	}
	
	@RequestMapping("/changePhone")
	@ResponseBody
	public int  changePhone(String phone,String uid){
		return userService.changePhone(phone,uid);
	}

	
}
